package com.cbb.display.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cbb.display.dto.DisplayDTO;
import com.cbb.display.dto.TrendDataDTO;
import com.cbb.display.entity.Funnel;
import com.cbb.display.entity.Goods;
import com.cbb.display.entity.GoodsType;
import com.cbb.display.entity.GoodsTypeRadio;
import com.cbb.display.entity.Region;
import com.cbb.display.entity.SaleTarget;
import com.cbb.display.entity.TodayData;
import com.cbb.display.entity.TotalData;
import com.cbb.display.service.FunnelService;
import com.cbb.display.service.GoodsService;
import com.cbb.display.service.GoodsTypeRadioService;
import com.cbb.display.service.GoodsTypeService;
import com.cbb.display.service.RegionService;
import com.cbb.display.service.SaleTargetService;
import com.cbb.display.service.TodayDataService;
import com.cbb.display.service.TotalDataService;
import com.cbb.display.util.CommonUtil;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bigbomb
 * @since 2020-02-01
 */
@RestController
@RequestMapping("/api")
public class ApiController {
	@Autowired
	private FunnelService funnelService;

	@Autowired
	private TodayDataService todayDataService;
	
	@Autowired
	private TotalDataService totalDataService;
	
	@Autowired
	private SaleTargetService saleTargetService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsTypeService goodsTypeService;
	
	@Autowired
	private GoodsTypeRadioService goodsTypeRadioService;
	
	@Autowired
	private RegionService regionService;
	@PostMapping("/get")
	public JSONObject get() {
	DisplayDTO displayDTO = new DisplayDTO();
    //当日统计 TodayData
	LocalDateTime dateTime = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); 
    String currentDate = dateTime.format(formatter);
	QueryWrapper<TodayData>	queryWrapper = new QueryWrapper();
	queryWrapper.apply("date_format(createdate,'%Y-%m-%d') = '"+currentDate+"'");
	List<TodayData> todayDataList = todayDataService.list(queryWrapper);
	Integer todayAddUserCount = todayDataList.stream().collect(Collectors.summingInt(TodayData::getTodayadduser));
	Integer todayplaceorderCount = todayDataList.stream().collect(Collectors.summingInt(TodayData::getTodayplaceorder));
	BigDecimal todayplaceorderamountCount = todayDataList.stream().map(TodayData::getTodayplaceorderamount).reduce(BigDecimal.ZERO,BigDecimal::add);
	TodayData todayData = TodayData.builder()
			.todayadduser(todayAddUserCount)
			.todayplaceorder(todayplaceorderCount)
			.todayplaceorderamount(todayplaceorderamountCount)
			.build();
	displayDTO.setTodayData(todayData);
	//月度销量趋势
	List<TodayData> todayDataMonthList = todayDataService.list();
	int currentMonthInteger = dateTime.getMonth().getValue();
	String monthplaceorderamountsum = "";//本月累计
	Map<Integer, List<TodayData>> resultByMonthList = todayDataMonthList.stream().collect(
	        Collectors.groupingBy(TodayData::getCreatemonth,TreeMap::new,Collectors.toList()));
	List<TreeMap<String, String>> acctMapList = new ArrayList<TreeMap<String,String>>();
    for (Entry<Integer, List<TodayData>> entry:resultByMonthList.entrySet()) {
    TreeMap<String, String> acctMap = new TreeMap<>();
      acctMap.put("name",entry.getKey().toString());
      acctMap.put("value",entry.getValue().stream().map(TodayData::getTodayplaceorderamount).reduce(BigDecimal.ZERO, BigDecimal::add).toString());
      QueryWrapper<SaleTarget> querySaleTargetWrapper = new QueryWrapper<SaleTarget>();
      querySaleTargetWrapper.eq("name", entry.getKey());
      SaleTarget saleTarget = saleTargetService.getOne(querySaleTargetWrapper);
      acctMap.put("targetvalue",saleTarget.getValue().toString());
      if(currentMonthInteger==entry.getKey())
        {
    	  monthplaceorderamountsum = acctMap.get("value");
        }
      acctMapList.add(acctMap);
    }
    Integer targetmonthplaceorderamountsum =0;
    QueryWrapper<SaleTarget> querySaleTargetWrapper = new QueryWrapper<SaleTarget>();
    querySaleTargetWrapper.eq("name", currentMonthInteger);
    SaleTarget saleTarget = saleTargetService.getOne(querySaleTargetWrapper);
    targetmonthplaceorderamountsum = saleTarget.getValue();//本月目标
    TrendDataDTO trendDataDTO = new TrendDataDTO();
    trendDataDTO.setAllMonthData(acctMapList);
    trendDataDTO.setCurrentMoney(monthplaceorderamountsum.toString());
    trendDataDTO.setTargetMoneyString(targetmonthplaceorderamountsum.toString());
    displayDTO.setTrendDataDTO(trendDataDTO);
   
	//总计数据
    QueryWrapper<TotalData>	queryTotalWrapper = new QueryWrapper();
	TotalData totalData = totalDataService.getOne(queryTotalWrapper);
	displayDTO.setTotalData(totalData);
	//用户流量转化率
	List<Funnel> funnelList = new ArrayList<Funnel>();
	funnelList = funnelService.list();
	displayDTO.setFunnel(funnelList);
	//各平台销量占比
	Map<String, List<TodayData>> resultByOrderFromList = todayDataMonthList.stream().collect(
	        Collectors.groupingBy(TodayData::getOrderfrom,TreeMap::new,Collectors.toList()));
	List<TreeMap<String, String>> acctMap1List = new ArrayList<TreeMap<String,String>>();
    for (Entry<String, List<TodayData>> entry:resultByOrderFromList.entrySet()) {
    	TreeMap<String, String> acctMap1 = new TreeMap<>();
    	BigDecimal entryTodayData = new BigDecimal(0);
    	entryTodayData = entry.getValue().stream().map(TodayData::getTodayplaceorderamount).reduce(BigDecimal.ZERO, BigDecimal::add);
    	acctMap1.put("name",entry.getKey().toString());
        acctMap1.put("value",entryTodayData.toString());
        acctMap1.put("per",entryTodayData.divide(totalData.getOrderfinishedamount(), 2, RoundingMode.HALF_UP).toString());
        acctMap1List.add(acctMap1);
    }

    displayDTO.setOrderFromListPer(acctMap1List);
    //产品销量排名
    List<Goods> goodsList = new ArrayList<Goods>();
    goodsList = goodsService.list();
    displayDTO.setGoodsList(goodsList);
    //产品类型排名
    List<GoodsType> goodsTypeList = new ArrayList<GoodsType>();
    goodsTypeList = goodsTypeService.list();
    displayDTO.setGoodsTypeList(goodsTypeList);
  //产品类型排名
    List<GoodsTypeRadio> goodsTypeRadioList = new ArrayList<GoodsTypeRadio>();
    goodsTypeRadioList = goodsTypeRadioService.list();
    displayDTO.setGoodsTypeRadioList(goodsTypeRadioList);
    
    //飞线图
    Map<String, String> regionMap = new HashMap<String, String>();
    List<Region> regionList = new ArrayList<Region>();
    List<List<Object>> flyregionList = new ArrayList<List<Object>>();
    regionList = regionService.list();
   
    for(Region region:regionList)
    {
    	List<Object> flyvaList = new ArrayList<Object>(2);
    	regionMap.put("name", "上海");
    	flyvaList.add(regionMap);
    	flyvaList.add(region);
    	flyregionList.add(flyvaList);
    }
    displayDTO.setFlyVal(flyregionList);
	
	return CommonUtil.successJson(displayDTO);
		
	}
}
